package pr.platerecognization;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Outline;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewOutlineProvider;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import org.opencv.android.OpenCVLoader;
import org.opencv.android.Utils;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import static android.graphics.Color.rgb;
import static android.view.MotionEvent.ACTION_DOWN;
import static android.view.MotionEvent.ACTION_UP;
import static java.lang.System.currentTimeMillis;

public class MainActivity extends Activity implements  View.OnClickListener, View.OnTouchListener {

    // Used to load the 'native-lib' library on application startup.
    static {

        if (OpenCVLoader.initDebug()) {
            Log.d("Opencv", "opencv load_success");

        } else {
            Log.d("Opencv", "opencv can't load opencv .");

        }
    }
    long touchDown;
    boolean onAsk = true;
    View allRe;
    int dpToPixels(float dp) {
        return (int) (getResources().getDisplayMetrics().density * dp + 0.5f);
    }
    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    void setViewRadius(final int radius, int... ids) {

        for (int id : ids) {
            View view = findViewById(id);
            view.setOutlineProvider(new ViewOutlineProvider() {
                @Override
                public void getOutline(View view, Outline outline) {
                    outline.setRoundRect(0, 0, view.getWidth(), view.getHeight(), radius);
                }
            });

            view.setClipToOutline(true);
        }
    }
    int[] buttonIds = {
            R.id.ToPhoto_Button_On_MainActivity,
            R.id.ToPick_Button_On_MainActivity
    };
    int[] askButtonIds = {
            R.id.OnLine_Button_On_MainActivity,
            R.id.OffLine_Button_On_MainActivity
    };
    public Button btn;
    public Button recogBtn;
    public TextView resbox;
    public TextView runtimebox;
    public ImageView imgv;
//    public SeekBar sb;
    private static final int REQUEST_CODE_IMAGE_CAMERA = 1;
    private static final int REQUEST_CODE_IMAGE_OP = 2;
    private static final int REQUEST_CODE_OP = 3;
    private Uri mPath;
    Bitmap latestBitmap;
    String mFilePath;
//    public  PlateRecognition pr;
    public long handle;
    private final String TAG = this.getClass().toString();
    private static String[][] fullNames;
    static {
        fullNames = new String[][]{
                {"安徽省", "皖"},
                {"北京市", "京"},
                {"福建省", "闽"},
                {"甘肃省", "甘"},
                {"广东省", "粤"},
                {"广西壮族自治区", "桂"},
                {"贵州省", "贵"},
                {"海南省", "琼"},
                {"河北省", "冀"},
                {"河南省", "豫"},
                {"黑龙江省", "黑"},
                {"湖北省", "鄂"},
                {"湖南省", "湘"},
                {"吉林省", "吉"},
                {"江苏省", "苏"},
                {"江西省", "赣"},
                {"辽宁省", "辽"},
                {"内蒙古自治区", "蒙"},
                {"宁夏回族自治区", "宁"},
                {"青海省", "青"},
                {"山东省", "鲁"},
                {"山西省", "晋"},
                {"陕西省", "陕"},
                {"上海市", "沪"},
                {"四川省", "川"},
                {"天津市", "津"},
                {"西藏自治区", "藏"},
                {"新疆维吾尔自治区", "新"},
                {"云南省", "云"},
                {"浙江省", "浙"},
                {"重庆市", "渝"}
        };
    }
    private static final Map<String, String[][]> cities = new HashMap<>(fullNames.length);
    static {

        cities.put("皖", new String[][]{
                {"A", "合肥市"},
                {"B", "芜湖市"},
                {"C", "蚌埠市"},
                {"D", "淮南市"},
                {"E", "马鞍山市"},
                {"F", "淮北市"},
                {"G", "铜陵市"},
                {"H", "安庆市"},
                {"J", "黄山市"},
                {"K", "阜阳市"},
                {"L", "宿州市"},
                {"M", "滁州市"},
                {"N", "六安市"},
                {"P", "宣城市"},
                {"Q", "巢湖市"},
                {"R", "池州市"},
                {"S", "毫州市"}

        });

        cities.put("京", new String[][]{
                {"A", ""},
                {"B", ""},
                {"C", ""},
                {"E", ""}
        });


        cities.put("闽", new String[][]{
                {"A", "福州市"},
                {"B", "莆田市"},
                {"C", "泉州市"},
                {"D", "厦门市"},
                {"E", "漳州市"},
                {"F", "龙岩市"},
                {"G", "三明市"},
                {"H", "南平市"},
                {"J", "宁德市"},
                {"K", "省直系统"}

        });

        cities.put("甘", new String[][]{
                {"A", "兰州市"},
                {"B", "嘉峪关市"},
                {"C", "金昌市"},
                {"D", "白银市"},
                {"E", "天水市"},
                {"F", "酒泉市"},
                {"G", "张掖市"},
                {"H", "威武市"},
                {"J", "定西市"},
                {"K", "陇南市"},
                {"L", "平凉市"},
                {"M", "庆阳市"},
                {"N", "临夏回族自治州"},
                {"P", "甘南藏族自治州"}

        });


        cities.put("粤", new String[][]{
                {"A", "广州市"},
                {"B", "深圳市"},
                {"C", "珠海市"},
                {"D", "汕头市"},
                {"E", "佛山市"},
                {"F", "韶关市"},
                {"G", "湛江市"},
                {"H", "肇庆市"},
                {"J", "江门市"},
                {"K", "茂名市"},
                {"L", "惠州市"},
                {"M", "梅州市"},
                {"N", "汕尾市"},
                {"P", "河源市"},
                {"Q", "阳江市"},
                {"R", "清远市"},
                {"S", "东莞市"},
                {"T", "中山市"},
                {"U", "潮州市"},
                {"V", "揭阳市"},
                {"W", "云浮市"},
                {"X", "顺德区"},
                {"Y", "南海区"},
                {"Z", "港澳进入内地车辆"}

        });


        cities.put("桂", new String[][]{
                {"A", "南宁市"},
                {"B", "柳州市"},
                {"C", "桂林市"},
                {"D", "梧州市"},
                {"E", "北海市"},
                {"F", "南宁地区"},
                {"G", "柳州地区"},
                {"H", "桂林地区"},
                {"J", "贺州市"},
                {"K", "玉林市"},
                {"L", "百色市"},
                {"M", "河池市"},
                {"N", "钦州市"},
                {"P", "防城港市"},
                {"R", "贵港市"}

        });


        cities.put("贵", new String[][]{
                {"A", "贵阳市"},
                {"B", "六盘水市"},
                {"C", "遵义市"},
                {"D", "铜仁市"},
                {"E", "黔西南布依族自治州"},
                {"F", "毕节市"},
                {"G", "安顺市"},
                {"H", "黔东南苗族侗族自治州"},
                {"J", "黔南布依族自治州"}

        });


        cities.put("琼", new String[][]{
                {"A", "海口市"},
                {"B", "三亚市"},
                {"C", "琼海市"},
                {"D", "五指山市"},
                {"E", "洋浦开发区"}

        });


        cities.put("冀", new String[][]{
                {"A", "石家庄市"},
                {"B", "唐山市"},
                {"C", "秦皇岛市"},
                {"D", "邯郸市"},
                {"E", "邢台市"},
                {"F", "保定市"},
                {"G", "张家口市"},
                {"H", "承德市"},
                {"J", "沧州市"},
                {"R", "廊坊市"},
                {"S", "沧州市"},
                {"T", "衡水市"}

        });


        cities.put("豫", new String[][]{
                {"A", "郑州市"},
                {"B", "开封市"},
                {"C", "洛阳市"},
                {"D", "平顶山市"},
                {"E", "安阳市"},
                {"F", "鹤壁市"},
                {"G", "新乡市"},
                {"H", "焦作市"},
                {"J", "濮阳市"},
                {"K", "许昌市"},
                {"L", "漯河市"},
                {"M", "三门峡市"},
                {"N", "商丘市"},
                {"P", "周口市"},
                {"Q", "驻马店市"},
                {"R", "南阳市"},
                {"S", "信阳市"},
                {"U", "济源市"}

        });


        cities.put("黑", new String[][]{
                {"A", "哈尔滨市"},
                {"B", "齐齐哈尔市"},
                {"C", "牡丹江市"},
                {"D", "佳木斯市"},
                {"E", "大庆市"},
                {"F", "伊春市"},
                {"G", "鸡西市"},
                {"H", "鹤岗市"},
                {"J", "双鸭山市"},
                {"K", "七台河市"},
                {"L", "松花江地区——已并入哈尔滨市"},
                {"M", "绥化市"},
                {"N", "黑河市"},
                {"P", "大兴安岭地区"},
                {"R", "农恳地区"}

        });
        cities.put("鄂", new String[][]{
                {"A", "武汉市"},
                {"B", "黄石市"},
                {"C", "十堰市"},
                {"D", "荆州市"},
                {"E", "宜昌市"},
                {"F", "襄樊市"},
                {"G", "鄂州市"},
                {"H", "荆门市"},
                {"J", "黄冈市"},
                {"K", "孝感市"},
                {"L", "咸宁市"},
                {"M", "仙桃市"},
                {"N", "潜江市"},
                {"P", "神农架林区"},
                {"Q", "恩施土家族苗族自治州"},
                {"R", "天门市"},
                {"S", "随州市"}

        });
        cities.put("湘", new String[][]{
                {"A", "长沙市"},
                {"B", "株洲市"},
                {"C", "湘潭市"},
                {"D", "衡阳市"},
                {"E", "邵阳市"},
                {"F", "岳阳市"},
                {"G", "张家界市"},
                {"H", "益阳市"},
                {"J", "常德市"},
                {"K", "娄底市"},
                {"L", "郴州市"},
                {"M", "永州市"},
                {"N", "怀化市"},
                {"U", "湘西土家族苗族自治州"}

        });
        cities.put("吉", new String[][]{
                {"A", "长春市"},
                {"B", "吉林市"},
                {"C", "四平市"},
                {"D", "辽源市"},
                {"E", "通化市"},
                {"F", "白山市"},
                {"G", "白城市"},
                {"H", "延边朝鲜族自治州"},
                {"J", "松原市"}

        });
        cities.put("苏", new String[][]{
                {"A", "南京市"},
                {"B", "无锡市"},
                {"C", "徐州市"},
                {"D", "常州市"},
                {"E", "苏州市"},
                {"F", "南通市"},
                {"G", "连云港市"},
                {"H", "淮安市"},
                {"J", "盐城市"},
                {"K", "扬州市"},
                {"L", "镇江市"},
                {"M", "泰州市"},
                {"U", "苏州市增补"}

        });
        cities.put("赣", new String[][]{
                {"A", "南昌市"},
                {"B", "赣州市"},
                {"C", "宜春市"},
                {"D", "吉安市"},
                {"E", "上饶市"},
                {"F", "抚州市"},
                {"G", "九江市"},
                {"H", "景德镇市"},
                {"J", "萍乡市"},
                {"K", "新余市"},
                {"L", "鹰潭市"},
                {"M", "南昌市，省直系统"}

        });
        cities.put("辽", new String[][]{
                {"A", "沈阳市"},
                {"B", "大连市"},
                {"C", "鞍山市"},
                {"D", "抚顺市"},
                {"E", "本溪市"},
                {"F", "丹东市"},
                {"G", "锦州市"},
                {"H", "营口市"},
                {"J", "阜新市"},
                {"K", "辽阳市"},
                {"L", "盘锦市"},
                {"M", "铁岭市"},
                {"N", "朝阳市"},
                {"P", "葫芦岛市"}

        });
        cities.put("蒙", new String[][]{
                {"A", "呼和浩特市"},
                {"B", "包头市"},
                {"C", "乌海市"},
                {"D", "赤峰市"},
                {"E", "呼伦贝尔市"},
                {"F", "兴安盟"},
                {"G", "通辽市"},
                {"H", "锡林郭勒盟"},
                {"J", "乌兰察布盟"},
                {"K", "鄂尔多斯市"},
                {"L", "巴彦淖尔盟"},
                {"M", "阿拉善盟"}

        });
        cities.put("宁", new String[][]{
                {"A", "银川市"},
                {"B", "石嘴山市"},
                {"C", "银南市"},
                {"D", "固原市"},
                {"E", "中卫市"}

        });
        cities.put("青", new String[][]{
                {"A", "西宁市"},
                {"B", "海东市"},
                {"C", "海北藏族自治州"},
                {"D", "黄南藏族自治州"},
                {"E", "海南藏族自治州"},
                {"F", "果洛藏族自治州"},
                {"G", "玉树藏族自治州"},
                {"H", "海西蒙古族藏族自治州"}

        });
        cities.put("鲁", new String[][]{
                {"A", "济南市"},
                {"B", "青岛市"},
                {"C", "淄博市"},
                {"D", "枣庄市"},
                {"E", "东营市"},
                {"F", "烟台市"},
                {"G", "潍坊市"},
                {"H", "济宁市"},
                {"J", "泰安市"},
                {"K", "威海市"},
                {"L", "日照市"},
                {"M", "滨州市"},
                {"N", "德州市"},
                {"P", "聊城市"},
                {"Q", "临沂市"},
                {"R", "菏泽市"},
                {"S", "莱芜市"},
                {"U", "青岛市增补"},
                {"V", "潍坊市增补"}

        });
        cities.put("晋", new String[][]{
                {"A", "太原市"},
                {"B", "大同市"},
                {"C", "阳泉市"},
                {"D", "长治市"},
                {"E", "晋城市"},
                {"F", "朔州市"},
                {"G", "雁北地区"},
                {"H", "忻州市"},
                {"J", "吕梁地区"},
                {"K", "晋中市"},
                {"L", "临汾市"},
                {"M", "运城市"}

        });
        cities.put("陕", new String[][]{
                {"A", "西安市"},
                {"B", "铜川市"},
                {"C", "宝鸡市"},
                {"D", "咸阳市"},
                {"E", "渭南市"},
                {"F", "汉中市"},
                {"G", "安康市"},
                {"H", "商洛市"},
                {"J", "延安市"},
                {"K", "榆林市"},
                {"V", "杨凌高新农业示范区"}

        });
        cities.put("沪", new String[][]{
                {"A", ""},
                {"B", ""},
                {"C", ""},
                {"D", ""},
                {"R", "崇明、长兴"}

        });
        cities.put("川", new String[][]{
                {"A", "成都市"},
                {"B", "绵阳市"},
                {"C", "自贡市"},
                {"D", "攀枝花市"},
                {"E", "沪州市"},
                {"F", "德阳市"},
                {"G", "成都市增补"},
                {"H", "广元市"},
                {"J", "遂宁市"},
                {"K", "内江市"},
                {"L", "乐山市"},
                {"M", "资阳市"},
                {"Q", "宜宾市"},
                {"R", "南充市"},
                {"S", "达州市"},
                {"T", "雅安市"},
                {"U", "阿坝藏族羌族自治州"},
                {"V", "甘孜藏族自治州"},
                {"W", "凉山彝族自治州"},
                {"X", "广安市"},
                {"Y", "巴中市"},
                {"Z", "眉山市"}

        });
        cities.put("津", new String[][]{
                {"A", ""},
                {"B", ""},
                {"C", ""}

        });
        cities.put("藏", new String[][]{
                {"A", "拉萨市"},
                {"B", "昌都地区"},
                {"C", "山南地区"},
                {"D", "日喀则地区"},
                {"E", "那曲地区"},
                {"F", "阿里地区"},
                {"G", "林芝地区"},
                {"H", "驻四川省天全县车辆管理所"},
                {"J", "驻青海省格尔木市车辆管理所"}

        });
        cities.put("新", new String[][]{
                {"A", "乌鲁木齐市"},
                {"B", "昌吉回族自治州"},
                {"C", "石河子市"},
                {"D", "奎屯市"},
                {"E", "博尔塔拉蒙古自治州"},
                {"F", "伊犁哈萨克自治州直辖县"},
                {"G", "塔城市"},
                {"H", "阿勒泰市"},
                {"J", "克拉玛依市"},
                {"K", "吐鲁番市"},
                {"L", "哈密市"},
                {"M", "巴音郭楞蒙古自治州"},
                {"N", "阿克苏市"},
                {"P", "克孜勒苏柯尔克孜自治州"},
                {"Q", "喀什市"},
                {"R", "和田市"}

        });
        cities.put("云", new String[][]{
                {"A", "昆明市"},
                {"A-V", "东川市"},
                {"C", "昭通市"},
                {"D", "曲靖市"},
                {"E", "楚雄彝族自治州"},
                {"F", "玉溪市"},
                {"G", "红河哈尼族彝族自治州"},
                {"H", "文山壮族苗族自治州"},
                {"J", "思茅市"},
                {"K", "西双版纳傣族自治州"},
                {"L", "大理白族自治州"},
                {"M", "保山市"},
                {"N", "德宏傣族景颇族自治州"},
                {"P", "丽江市"},
                {"Q", "怒江傈僳族自治州"},
                {"R", "迪庆藏族自治州"},
                {"S", "临沧地区"}

        });
        cities.put("浙", new String[][]{
                {"A", "杭州市"},
                {"B", "宁波市"},
                {"C", "温州市"},
                {"D", "绍兴市"},
                {"E", "湖州市"},
                {"F", "嘉兴市"},
                {"G", "金华市"},
                {"H", "衢州市"},
                {"J", "台州市"},
                {"K", "丽水市"},
                {"L", "舟山市"}

        });
        cities.put("渝", new String[][]{
                {"A", "市区（江南）"},
                {"B", "市区（江北）"},
                {"C", "永川区"},
                {"F", "万州区"},
                {"G", "涪陵区"},
                {"H", "黔江区"}
        });
    }
    public void copyFilesFromAssets(Context context, String oldPath, String newPath) {
        try {
            String[] fileNames = context.getAssets().list(oldPath);
            if (fileNames.length > 0) {
                // directory
                File file = new File(newPath);
                if (!file.mkdir()) {
                    Log.d("mkdir", "can't make folder");

                }
//                    return false;                // copy recursively
                for (String fileName : fileNames) {
                    copyFilesFromAssets(context, oldPath + "/" + fileName,
                            newPath + "/" + fileName);
                }
            } else {
                // file
                InputStream is = context.getAssets().open(oldPath);
                FileOutputStream fos = new FileOutputStream(new File(newPath));
                byte[] buffer = new byte[1024];
                int byteCount;
                while ((byteCount = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, byteCount);
                }
                fos.flush();
                is.close();
                fos.close();
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public void initRecognizer() {
        String assetPath = "pr";
        String sdcardPath = Environment.getExternalStorageDirectory()
                + File.separator + assetPath;
        copyFilesFromAssets(this, assetPath, sdcardPath);
        String cascade_filename = sdcardPath
                + File.separator + "cascade.xml";
        String finemapping_prototxt = sdcardPath
                + File.separator + "HorizonalFinemapping.prototxt";
        String finemapping_caffemodel = sdcardPath
                + File.separator + "HorizonalFinemapping.caffemodel";
        String segmentation_prototxt = sdcardPath
                + File.separator + "Segmentation.prototxt";
        String segmentation_caffemodel = sdcardPath
                + File.separator + "Segmentation.caffemodel";
        String character_prototxt = sdcardPath
                + File.separator + "CharacterRecognization.prototxt";
        String character_caffemodel = sdcardPath
                + File.separator + "CharacterRecognization.caffemodel";
        handle = PlateRecognition.InitPlateRecognizer(
                cascade_filename,
                finemapping_prototxt, finemapping_caffemodel,
                segmentation_prototxt, segmentation_caffemodel,
                character_prototxt, character_caffemodel
        );
    }
    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context       The context.
     * @param uri           The Uri to query.
     * @param selection     (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri
     * @return
     */
    private String getPath(Uri uri) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (DocumentsContract.isDocumentUri(this, uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                    return null;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                    return null;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{
                        split[1]
                };

                return getDataColumn(this, contentUri, selection, selectionArgs);
            }
        }
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor actualimagecursor = managedQuery(uri, proj, null, null, null);
        int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        actualimagecursor.moveToFirst();
        String img_path = actualimagecursor.getString(actual_image_column_index);
        String end = img_path.substring(img_path.length() - 4);
        if (0 != end.compareToIgnoreCase(".jpg") && 0 != end.compareToIgnoreCase(".png")) {
            return null;
        }
        return img_path;
    }
    public static Bitmap decodeImage(String path) {
        Bitmap res;
        try {
            ExifInterface exif = new ExifInterface(path);
            int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);

            BitmapFactory.Options op = new BitmapFactory.Options();
            op.inSampleSize = 1;
            op.inJustDecodeBounds = false;
            //op.inMutable = true;
            res = BitmapFactory.decodeFile(path, op);
            //rotate and scale.
            Matrix matrix = new Matrix();

            if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
                matrix.postRotate(90);
            } else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
                matrix.postRotate(180);
            } else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
                matrix.postRotate(270);
            }

            Bitmap temp = Bitmap.createBitmap(res, 0, 0, res.getWidth(), res.getHeight(), matrix, true);
            Log.d("com.arcsoft", "check target Image:" + temp.getWidth() + "X" + temp.getHeight());

            if (!temp.equals(res)) {
                res.recycle();
            }
            return temp;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public void SimpleRecog(Bitmap bmp,float size) {
try{
        float dp_asp = size;
        imgv.setImageBitmap(bmp);
//        Mat mat_src = new Mat(bmp.getWidth(), bmp.getHeight(), CvType.CV_8UC1);
        Mat mat_src = new Mat(bmp.getWidth(), bmp.getHeight(), CvType.CV_8UC4);

        float new_w = bmp.getWidth() * dp_asp;
        float new_h = bmp.getHeight() * dp_asp;
        Size sz = new Size(new_w, new_h);
        Utils.bitmapToMat(bmp, mat_src);
        Imgproc.resize(mat_src, mat_src, sz);
        long currentTime1 = System.currentTimeMillis();
        String res = PlateRecognition.SimpleRecognization(mat_src.getNativeObjAddr(), handle);
        long diff = System.currentTimeMillis() - currentTime1;
        if (res.equals(null)||res.equals(""))
        {
            resbox.setText("无法识别");
        }
        else {
            String[] city = allresult(res);
            String result = "";
            for (int i = 0; i < city.length; i++) {
                result += city[i] + "\n";
            }
            resbox.setText("识别结果\n" + result );
            runtimebox.setText(String.valueOf(diff) + "ms");
        }

        }
catch (Exception e)
{
    resbox.setText("图片??????");
}
    }
    private String[] allresult(String res) {
        String[] xx=res.split(",");
        String[] result = new String[xx.length];
        for (int i=0;i<xx.length;i++)
        {
           result[i]=xx[i]+"\n签发地区:"+StaCi(xx[i].substring(0,1),xx[i].substring(1,2));
        }
        return result;
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_IMAGE_OP && resultCode == RESULT_OK) {
            mPath = data.getData();
            String file = getPath(mPath);
            Bitmap bmp = decodeImage(file);
            if (bmp == null || bmp.getWidth() <= 0 || bmp.getHeight() <= 0) {
                Log.e(TAG, "error");
            } else {
                Log.i(TAG, "bmp [" + bmp.getWidth() + "," + bmp.getHeight());
            }
            latestBitmap = bmp;
            SimpleRecog(bmp,0.58f);
//            startOilPainting(bmp, file);
        } else if (requestCode == REQUEST_CODE_OP) {
            Log.i(TAG, "RESULT =" + resultCode);
            if (data == null) {
                return;
            }
            Bundle bundle = data.getExtras();
            String path = bundle.getString("imagePath");
            Log.i(TAG, "path=" + path);
        } else if (requestCode == REQUEST_CODE_IMAGE_CAMERA && resultCode == RESULT_OK) {
//            String file = getPath(mPath);
//            Bitmap bmp = decodeImage(file);
//            latestBitmap = bmp;
            FileInputStream is=null;
            File tempFile=null;
            try {
                tempFile=new File(mFilePath, "temp.jpg");
                 is= new FileInputStream(tempFile);
                //不同的构造方法而已
            }catch (IOException e){
                e.printStackTrace();
            }finally {
                try {
                    if(is!=null)
                        is.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
            Bitmap bitmap = decodeImage(tempFile.getAbsolutePath());
            SimpleRecog(bitmap,0.8f);
            tempFile.delete();
            /**
             * Android 9.0试试
             */
//            startOilPainting(bmp, file);
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR|
                View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR|
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ask);
        String permission = Manifest.permission.WRITE_EXTERNAL_STORAGE;
        if (ActivityCompat.checkSelfPermission(MainActivity.this, permission)
                != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]
                    {permission}, 123);

        }
        initRecognizer();
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    public void onResume() {
        super.onResume();
        if (!onAsk) {
            btn = findViewById(R.id.ToPick_Button_On_MainActivity);
            recogBtn = findViewById(R.id.ToPhoto_Button_On_MainActivity);
            imgv = findViewById(R.id.ImageView_On_MainActivity);
            resbox = (TextView) findViewById(R.id.ShowResult_TextView_On_MainActivity);
            runtimebox = (TextView) findViewById(R.id.ShowTime_TextView_On_MainActivity);
            /**
             *
             */

            for (int id : buttonIds)
                findViewById(id).setOnTouchListener(this);
            setViewRadius(dpToPixels(15), buttonIds);
            allRe = findViewById(R.id.All_Re_On_Main);
            allRe.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), android.R.anim.fade_in));
            allRe.setVisibility(View.VISIBLE);
        } else {
            for (int id : askButtonIds)
                findViewById(id).setOnTouchListener(this);
            setViewRadius(dpToPixels(15), askButtonIds);
        }
    }




    /**
     * 按钮点击事件
     *
     * @param v
     */
    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.OffLine_Button_On_MainActivity:
                setContentView(R.layout.activity_main);
                onAsk = false;
                onResume();
                break;
            case R.id.OnLine_Button_On_MainActivity:
                Intent intent = new Intent(getApplicationContext(), network.class);
                startActivity(intent);

                break;
            case R.id.ToPhoto_Button_On_MainActivity:
                mFilePath = getExternalFilesDir(Environment.DIRECTORY_PICTURES).getPath();
                try {
                    if (!new File(mFilePath).exists()) {
                        new File(mFilePath).mkdirs();
                        new File(mFilePath, "temp.jpg").createNewFile();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                // 指定拍照意图
                //先这样
                Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                Uri mUri ;

                if(Build.VERSION.SDK_INT>Build.VERSION_CODES.N)
                    mUri=FileProvider.getUriForFile(getApplicationContext(),BuildConfig.APPLICATION_ID+".PhotoProvider",new File(mFilePath,"temp.jpg"));
                else
                    mUri=Uri.fromFile(new File(mFilePath,"temp.jpg"));
                //再试试
                // 指定存储路径，这样就可以保存原图了
                openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
                startActivityForResult(openCameraIntent, REQUEST_CODE_IMAGE_CAMERA);

                /*Intent getImageByCamera = new Intent(
                        "android.media.action.IMAGE_CAPTURE");
                ContentValues values = new ContentValues(1);

                values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");

                mPath = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                getImageByCamera.putExtra(MediaStore.EXTRA_OUTPUT, mPath);
                startActivityForResult(getImageByCamera, REQUEST_CODE_IMAGE_CAMERA);*/
                break;

            /**
             *
             */
            case R.id.ToPick_Button_On_MainActivity:
                /**
                 * 选择图片按钮
                 */

                startActivityForResult(new Intent(Intent.ACTION_PICK).setType("image/*"),REQUEST_CODE_IMAGE_OP);

            default:
                break;
        }
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == ACTION_DOWN) {
            v.setBackgroundColor(rgb(246, 246, 246));
            ((Button) v).setTextColor(getResources().getColor(R.color.colorAccent));
            touchDown = currentTimeMillis();
        } else if (event.getAction() == ACTION_UP) {
            v.setBackgroundColor(getResources().getColor(R.color.colorAccent));
            ((Button) v).setTextColor(Color.WHITE);
            if (currentTimeMillis() - touchDown <= 500)
                onClick(v);
        }
        return false;
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onBackPressed() {
        if (!onAsk) {
            onAsk = true;
            allRe.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), android.R.anim.fade_out));
            allRe.setVisibility(View.GONE);
            setContentView(R.layout.ask);
            onResume();
        } else
            super.onBackPressed();
    }

    private static String StaCi(String C, String l) {
        String result = "";
        for (int x = 0; x < fullNames.length; x++) {
            if (C.equals(fullNames[x][1])) {
                result += fullNames[x][0];
            }
        }
        String[][] temp = cities.get(C);
        for (int s = 0; s < temp.length; s++) {
            if (l.equals(temp[s][0])) {
                result += temp[s][1];
            }
        }
        return result;
    }
}

